package com.ruoyi.api.controller;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.github.benmanes.caffeine.cache.LoadingCache;
import com.ruoyi.api.common.Result;
import com.ruoyi.api.common.ResultGenerator;
import com.ruoyi.api.config.NacosDynamicConf;
import lombok.extern.slf4j.Slf4j;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.TimeUnit;

@RestController
@Slf4j
public class APIController {

    public static final String YYYYMMDDHHMMSS = "yyyyMMddHHmmss";
    /**
     * 获取系统时间的缓存
     */
    private final String  getTimeCacheKey = "getSystemTime";

    @Autowired
    private LoadingCache cache;

    @Autowired
    private NacosDynamicConf nacosDynamicConf;

    /**
     * http://localhost:8082/api/service/getSystemTime
     * @return
     */
    @RequestMapping("/api/service/getSystemTime")
    public String getSystemTime() throws InterruptedException {
        Map<String, Object> map = new HashMap<>(2);

        Random random = new Random();
        int count = random.nextInt(10);
        TimeUnit.MILLISECONDS.sleep(count * 100);

        Object o = cache.getIfPresent(getTimeCacheKey);
        if (o != null){
            log.info("use cache...");
            map.put("time", o);
            map.put("cacheTime", true);
        }else {
            log.info("no cache or Expire");
            String time = DateTime.now().toString(YYYYMMDDHHMMSS);
            map.put("time", time);
            map.put("cacheTime", false);
            cache.put(getTimeCacheKey,time);
        }
        Result result = ResultGenerator.genSuccessResult(map);
        return JSON.toJSONString(result,SerializerFeature.BrowserCompatible,SerializerFeature.WriteNonStringValueAsString);
    }
}
